import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import Storehouse

# 仓库管理视图
# Create your views here.


@xframe_options_exempt
def index(request):
    return render(request, "storehouse/index.html")


def storehouse_list(request):
    result = {"status": 1, "msg": "查询失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 5)
        search = data.get("search")

        pers = Storehouse.objects.filter(is_delete=0)
        if search and search != "":
            pers = pers.filter(name__contains=search)
        per_count = pers.count()
        paginator = Paginator(pers.order_by("-create_time"), limit)  # 每页多少条数据
        try:
            pers = paginator.page(page)  # 返回 page（页数）的数据
        except PageNotAnInteger:
            pers = paginator.page(1)  # 第一页
        except EmptyPage:
            pers = paginator.page(paginator.num_pages)  # 最后一页

        data_list = []
        for i in range(len(pers)):
            data_list.append({
                "No": i + 1,
                "id": pers[i].id,
                "name": pers[i].name,
                # "route": pers[i].route,
                "status": pers[i].status,
                "remark": pers[i].remark,
                "create_time": str(pers[i].create_time).split(".")[0],
            })

        result["data"] = data_list
        result["data_count"] = per_count
        result["status"] = 0  # layui parseData status=0 才认为是成功
        result["msg"] = "仓库列表查询成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def storehouse_add(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            name = data.get("name")
            remark = data.get("remark")
            route_exist = Storehouse.objects.filter(name=name, is_delete=0).first()
            if route_exist:
                result["msg"] = "该仓库已存在，请勿重复添加！"
                return JsonResponse(result)
            new_per = Storehouse(name=name, remark=remark)
            new_per.save()
            result["status"] = 1
            result["msg"] = "仓库添加成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        return render(request, "storehouse/add.html")


@xframe_options_exempt
def storehouse_edit(request, store_id=None):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            name = data.get("name")
            remark = data.get("remark")
            per = Storehouse.objects.filter(id=int(store_id), is_delete=0).first()
            if not per:
                result["msg"] = "请确认该仓库是否存在！"
                return JsonResponse(result)
            route_exist = Storehouse.objects.filter(name=name, is_delete=0).first()
            if route_exist:
                result["msg"] = "该仓库已存在！"
                return JsonResponse(result)
            if per.name != name:
                per.name = name
            if per.remark != remark:
                per.remark = remark
            per.save()
            result["status"] = 1
            result["msg"] = "仓库信息更改成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        store = Storehouse.objects.filter(id=int(store_id), is_delete=0).first()
        return render(request, "storehouse/edit.html", {"store": store})


def storehouse_del(request, store_id=None):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            per = Storehouse.objects.filter(id=int(store_id), is_delete=0).first()
            if per:
                per.is_delete = 1
                per.save()
                result["status"] = 1
                result["msg"] = "仓库删除成功！"
            else:
                result["msg"] = "请确认该仓库是否存在"
        except Exception as e:
            print(e)
    return JsonResponse(result)


def storehouse_status(request, store_id=None):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            print(data)
            status = data.get("status", None)
            if status is None or not isinstance(status, bool):
                result["msg"] = "请确认操作类型!"
                return JsonResponse(result)

            per = Storehouse.objects.filter(id=int(store_id), is_delete=0).first()
            if per:
                if status is True and per.status == 0:
                    per.status = 1
                if status is False and per.status == 1:
                    per.status = 0
                per.save()
                result["status"] = 1
                result["msg"] = "仓库启用成功!" if status is True else "仓库禁用成功！"
            else:
                result["msg"] = "请确认仓库是否正确!"
        except Exception as e:
            print(e)
    return JsonResponse(result)

